//
//  QXOAuthVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/25.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import SVProgressHUD

class QXOAuthVC: UIViewController, UIWebViewDelegate {

    private let wb_client_id = "2333485825"
    private let wb_redirect_uri = "http://www.baidu.com"
    private let wb_redirect_uris = "https://www.baidu.com"
    private let wb_app_secret = "a48c3dbe00b3bf1a3c998b79d6eb72ea"
    
    lazy var webView: UIWebView? = {
        let webv = UIWebView()
        webv.delegate = self
        return webv
    }()
    
    override func loadView() {
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
    }
    
    
    private func loadOAuthPage() {
        
        let urlStirng = "https://api.weibo.com/oauth2/authorize?client_id=\(wb_client_id)&redirect_uri=\(wb_redirect_uri)"
        
        let url = NSURL(string: urlStirng)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStirng = request.URL!.absoluteString
        
        // 如果不是回調URL，则继续加载（注意这里回調的时候，百度的网址会改变）
        if !urlStirng.hasPrefix(wb_redirect_uri) {
            return true
        }
        
        // 取得请求中的 查询字符串
        let query = request.URL!.query!
        let codePrefix = "code="
        
        if query.hasPrefix(codePrefix) {
            let code = query.substringFromIndex(advance(codePrefix.endIndex, 0))
            print("获取授权码 \(code)")
            loadAccessToken(code)
        } else {
            close()
        }
        
        return false
    }
    
    private func loadAccessToken(code: String) {
        
        let urlString = "oauth2/access_token"
        
        let params = [
            "client_id": wb_client_id,
            "client_secret": wb_app_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": wb_redirect_uri
        ]

        QXNetworking.sharedNetworking().POST(urlString, parameters: params, success: { (_, data) -> Void in
            
            let account = QXAccount(dic: data as! [String: AnyObject])
            
            account.loadUserInfo({ (account) -> () in
                self.success()
                }) { (error) -> () in
                    print(error)
                    self.failed()
            }
            
            }) { (_, error) -> Void in
            print(error)
            self.failed()
        }
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    func success() {
        SVProgressHUD.showInfoWithStatus("授权成功！")
        
        // false 表示跳转到欢迎
        NSNotificationCenter.defaultCenter().postNotificationName(QXAppDelegateChangeRootViewControllerNotification, object: false)
        close()
    }
    
    func failed() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力！")
        close()
    }

}
